package eteam.aps.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import eteam.aps.api.U8Api;
import eteam.aps.common.component.LoginUserRedisService;
import eteam.aps.common.constant.ArrivalType;
import eteam.aps.common.constant.QCAcceptType;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Assert;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JsonPage;
import eteam.aps.mapper.ArrivalVouchMapper;
import eteam.aps.mapper.ZnInLogMapper;
import eteam.aps.model.dto.ArrivalVouchDto;
import eteam.aps.model.dto.ArrivalVouchQueryDto;
import eteam.aps.model.dto.ArrivalVouchUpdateDto;
import eteam.aps.model.entity.arrival.ArrivalRep;
import eteam.aps.model.entity.arrival.ArrivalRepository;
import eteam.aps.model.entity.arrival.ArrivalVouch;
import eteam.aps.model.entity.arrival.ZnInLog;
import eteam.aps.model.vo.arrival.ArrivalRepositoryBody;
import eteam.aps.model.vo.arrival.ArrivalRepositoryVo;
import eteam.aps.model.vo.arrival.ArrivalVouchShowVo;
import eteam.aps.model.vo.arrival.ArrivalVouchVo;
import eteam.aps.service.ArrivalVouchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.json.JsonArray;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 到货单;U8到货单 业务层实现类
 *
 * @author LiuLei
 */
@Slf4j
@Service
public class ArrivalVouchServiceImpl implements ArrivalVouchService {

    @Autowired
    private ArrivalVouchMapper arrivalVouchMapper;

    @Autowired
    private ZnInLogMapper logMapper;

    @Autowired
    private LoginUserRedisService loginUserRedisService;

    //    @Override
//    @Transactional
//    public ArrivalVouchShowVo selByBar(String bar) throws Exception {
//        Map<String, Object> map = new HashMap<>(3);
//        map.put("bar", bar);
//        map.put("fState", ParentEntity.FSTATE_DELETED);
//        map.put("arrivalType", ArrivalType.DEFAULT);
//        ArrivalVouchShowVo arrivalVouchShowVo = arrivalVouchMapper.getOneByBar(map);
//        if (arrivalVouchShowVo == null) { // 没有 从接口获取
//            ArrivalDl arrivalDl = U8Api.getArrivalVouch(bar);
//            Assert.isEmpty(arrivalDl, "暂无数据！！");
//            if (arrivalDl.getSaveList() != null && !arrivalDl.getSaveList().isEmpty()) {
//                arrivalVouchMapper.saveArrivalList(arrivalDl.getSaveList());
//            }
//            Assert.isTrue(arrivalDl.getView() == null && arrivalDl.getView().isEmpty(), "暂无数据！！");
//            return BeanUtil.copyProperties(arrivalDl.getView().get(0), ArrivalVouchShowVo.class);
//        }
//        if (arrivalVouchShowVo.getfQCAceptType() != QCAcceptType.STORAGE) return arrivalVouchShowVo;
//        throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无需要质检的数据！");
//    }
    @Override
    @Transactional
    public ArrivalVouchShowVo selByBar(String bar) throws Exception {
        Map<String, Object> map = new HashMap<>(2);
        map.put("bar", bar);
        map.put("fState", ParentEntity.FSTATE_DELETED);
        ArrivalVouchShowVo arrivalVouchShowVo = arrivalVouchMapper.getOneByBar(map);
        if (arrivalVouchShowVo == null) { // 没有 从接口获取
            ArrivalVouch arrivalVouch = U8Api.getArrivalVouch(bar);
            Assert.isEmpty(arrivalVouch, "暂无数据！！");
            if (arrivalVouch.getQty() == null || arrivalVouch.getQty().compareTo(arrivalVouch.getfIQuantity()) == 0) {
                arrivalVouch.setfArrivalType(ArrivalType.DEFAULT);
            } else {
                arrivalVouch.setfArrivalType(ArrivalType.MERGE);
            }
            String fuserid = loginUserRedisService.getUser().fuserid;
            Helper.setDefaultAddValue(arrivalVouch, fuserid);
            arrivalVouchMapper.saveArrival(arrivalVouch);
            return BeanUtil.copyProperties(arrivalVouch, ArrivalVouchShowVo.class);
        }
        if (arrivalVouchShowVo.getfQCAceptType() != QCAcceptType.STORAGE) return arrivalVouchShowVo;
        throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无需要质检的数据！");
    }

    //    @Override
//    @Transactional
//    public List<ArrivalVouchShowVo> selByCode(String code) throws Exception {
//        Map<String, Object> map = new HashMap<>(2);
//        map.put("code", code);
//        map.put("fState", ParentEntity.FSTATE_DELETED);
//        Map<String, ArrivalVouchShowVo> arrivalVouchShowVoMap = arrivalVouchMapper.getOneByCode(map);
//        // 筛选出所有本地的到货单条码
//        List<ArrivalDl> arrivalDlList = U8Api.getArrivalVouchList(code);
//        if (arrivalDlList.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无此单据信息");
//        List<ArrivalVouch> saveList = new LinkedList<>();
//        // 遍历单据
//        for (ArrivalDl arrivalDl : arrivalDlList) {
//            // 获取所有展示项
//            List<ArrivalVouch> view = arrivalDl.getView();
//            if (view != null && !view.isEmpty()) {
//                // 遍历展示项
//                for (ArrivalVouch vouch : view) {
//                    // 判断是否已经有了 有了使用本地库，没有则使用u8
//                    if (!arrivalVouchShowVoMap.containsKey(vouch.getfBarCode())) {
//                        arrivalVouchShowVoMap.put(vouch.getfBarCode(), BeanUtil.copyProperties(vouch, ArrivalVouchShowVo.class));
//                        saveList.add(vouch);
//                    }
//                }
//            }
//            // 获取save
//            List<ArrivalVouch> save = arrivalDl.getSaveList();
//            if (save != null && !save.isEmpty()) {
//                Iterator<ArrivalVouch> iterator = save.iterator();
//                while (iterator.hasNext()) {
//                    ArrivalVouch next = iterator.next();
//                    // 获取条码
//                    String barCode = next.getfBarCode();
//                    // 已经存在
//                    if (arrivalVouchShowVoMap.containsKey(barCode)) {
//                        // 存在 就移除掉 本地库已经拥有了不需要保存
//                        iterator.remove();
//                        // 只要入库了就移除展示项
//                        ArrivalVouchShowVo vo = arrivalVouchShowVoMap.get(barCode);
//                        if (vo.getfQCAceptType() == QCAcceptType.STORAGE) arrivalVouchShowVoMap.remove(barCode);
//                    } else { // 不存在
//                        arrivalVouchShowVoMap.put(next.getfBarCode(), BeanUtil.copyProperties(next, ArrivalVouchShowVo.class));
//                    }
//                }
//            }
//        }
//        for (ArrivalDl arrivalDl : arrivalDlList) {
//            saveList.addAll(arrivalDl.getSaveList());
//        }
//        // 只要过滤出来的列表不为空 证明本地库没有 就保存 否则 证明本地库里面全有
//        if (!saveList.isEmpty()) arrivalVouchMapper.saveArrivalList(saveList);
//        // 只展示默认和合并的单据
//        List<ArrivalVouchShowVo> viewList = arrivalVouchShowVoMap.values().stream().filter(data -> data.getfArrivalType() >= ArrivalType.DEFAULT).collect(Collectors.toList());
//        if (viewList.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无需要质检的数据！");
//        return new LinkedList<>(viewList);
//    }
    @Override
    @Transactional
    public List<ArrivalVouchShowVo> selByCode(String code) throws Exception {
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", code);
        map.put("fState", ParentEntity.FSTATE_DELETED);
        List<ArrivalVouch> save = new ArrayList<>();
        List<ArrivalVouchShowVo> show = new ArrayList<>();
        Map<String, ArrivalVouchShowVo> arrivalVouchShowVoMap = arrivalVouchMapper.getOneByCode(map);
        arrivalVouchShowVoMap.values().forEach(data -> {
            if (data.getfQCAceptType() < QCAcceptType.STORAGE) {
                // 已入库 不需要查询出来
                show.add(BeanUtil.copyProperties(data, ArrivalVouchShowVo.class));
            }
        });
        // 筛选出所有本地的到货单条码
        List<ArrivalVouch> arrivalVouchList = U8Api.getArrivalVouchList(code);
        if (arrivalVouchShowVoMap.isEmpty() && arrivalVouchList.isEmpty())
            throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无此单据信息");
        // 去重本地库已经有的
        arrivalVouchList.stream().collect(Collectors.toMap(ArrivalVouch::getfBarCode, Function.identity())).forEach((key, value) -> {
            ArrivalVouchShowVo df = arrivalVouchShowVoMap.getOrDefault(key, null);
            // 本地没有
            if (Objects.isNull(df)) {
                if (value.getQty().compareTo(value.getfIQuantity()) == 0) {
                    value.setfArrivalType(ArrivalType.DEFAULT);
                } else {
                    value.setfArrivalType(ArrivalType.MERGE);
                }
                save.add(value);
                show.add(BeanUtil.copyProperties(value, ArrivalVouchShowVo.class));
            }
        });
        if (!save.isEmpty()) {
            String fuserid = loginUserRedisService.getUser().fuserid;
            save.forEach(data -> Helper.setDefaultAddValue(data, fuserid));
            arrivalVouchMapper.saveArrivalList(save);
        }
        return show;
    }


    @Override
    @Transactional
    public int updateAv(List<ArrivalVouchUpdateDto> list) throws Exception {
        String fuserid = loginUserRedisService.getUser().getFuserid();
        LocalDateTime now = LocalDateTime.now();
        List<Map<String, Object>> updateList = new ArrayList<>(list.size());
        for (ArrivalVouchUpdateDto arrivalVouchUpdateDto : list) {
            Helper.setEmptyWithNull(arrivalVouchUpdateDto);
            arrivalVouchUpdateDto.setfLastModifyUserId(fuserid);
            arrivalVouchUpdateDto.setfLastModifyTime(now);
            arrivalVouchUpdateDto.setfOperator(fuserid);
            arrivalVouchUpdateDto.setfFinStockQuantity(arrivalVouchUpdateDto.getfIQuantity().subtract(arrivalVouchUpdateDto.getfFinValidQuantity()));
            arrivalVouchUpdateDto.setfAuditorTime(now);
            if (arrivalVouchUpdateDto.getfICheckQuantity().compareTo(arrivalVouchUpdateDto.getfVaildQuantity()) == 0) {
                arrivalVouchUpdateDto.setfQtyRate(BigDecimal.ONE);
            } else {
                // 合格率 良品数/抽检数
                arrivalVouchUpdateDto.setfQtyRate(arrivalVouchUpdateDto.getfFinStockQuantity().divide(arrivalVouchUpdateDto.getfICheckQuantity(), 2, RoundingMode.CEILING));
            }
            Map<String, Object> update = new HashMap<>(3);
            update.put("stockQty", arrivalVouchUpdateDto.getfFinValidQuantity());
            update.put("barCode", arrivalVouchUpdateDto.getfBarCode());
            update.put("state", ParentEntity.FSTATE_DELETED);
            updateList.add(update);
        }
        if (!updateList.isEmpty()) arrivalVouchMapper.updateAvFFinStockQuantityByFirstBarCode(updateList);
        return arrivalVouchMapper.updateAvByArrivalVouchUpdateDto(list);
    }

    @Override
    public JsonPage<ArrivalVouchShowVo> selJSP(ArrivalVouchQueryDto arrivalVouchQueryDto) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("fState", ParentEntity.FSTATE_DELETED);
        // 条码号
        if (Helper.isNotEmpty(arrivalVouchQueryDto.getfBarCode()))
            map.put("fBarCode", arrivalVouchQueryDto.getfBarCode());
        // 工单号
        if (Helper.isNotEmpty(arrivalVouchQueryDto.getfCCode())) map.put("fCode", arrivalVouchQueryDto.getfCCode());
        // 品号
        if (Helper.isNotEmpty(arrivalVouchQueryDto.getFclnvCode()))
            map.put("fInvCode", arrivalVouchQueryDto.getFclnvCode());
        // 物料名称
        if (Helper.isNotEmpty(arrivalVouchQueryDto.getfProductName()))
            map.put("fProductName", Helper.likeSql(arrivalVouchQueryDto.getfProductName()));
        // 物料规格
        if (Helper.isNotEmpty(arrivalVouchQueryDto.getFclnvStd()))
            map.put("fInvStd", Helper.likeSql(arrivalVouchQueryDto.getFclnvStd()));
        // 开始时间
        if (arrivalVouchQueryDto.getStartTime() != null) map.put("startTime", arrivalVouchQueryDto.getStartTime());
        // 结束时间
        if (arrivalVouchQueryDto.getEndTime() != null) map.put("endTime", arrivalVouchQueryDto.getEndTime());
        // 验收状态
        if (arrivalVouchQueryDto.getAcceptState() != null)
            map.put("acceptState", arrivalVouchQueryDto.getAcceptState());
        // 出厂检验状态
        if (arrivalVouchQueryDto.getInsType() != null) map.put("insType", arrivalVouchQueryDto.getInsType());
        // 物料分类
        if (arrivalVouchQueryDto.getInvType() != null) map.put("invType", arrivalVouchQueryDto.getInvType());
        // 采购方
        if (arrivalVouchQueryDto.getPurName() != null) map.put("purName", arrivalVouchQueryDto.getPurName());
        int count = arrivalVouchMapper.selCount(map);
        if (count == 0)
            JsonPage.builder(arrivalVouchQueryDto.getPage(), arrivalVouchQueryDto.getSize(), count, Collections.emptyList());
        map.put("size", arrivalVouchQueryDto.getSize());
        map.put("offSize", arrivalVouchQueryDto.offSize());
        List<ArrivalVouchShowVo> list = arrivalVouchMapper.selJsp(map);
        return JsonPage.builder(arrivalVouchQueryDto.getPage(), arrivalVouchQueryDto.getSize(), count, list);
    }

    @Override
    public Set<ArrivalVouch> selPurByBar(String bar) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("bar", bar);
        map.put("fState", ParentEntity.FSTATE_DELETED);
        map.put("type", QCAcceptType.ALLOWED);
        map.put("arrivalType", ArrivalType.DEFAULT);
        List<ArrivalVouch> arrivalVouchList = arrivalVouchMapper.getOneByPurBarCode(map);
        if (arrivalVouchList.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无数据！");
        Set<ArrivalVouch> result = new HashSet<>();
        List<String> mergeBarList = arrivalVouchList.stream().filter(data -> {
            if (ArrivalType.MERGE != data.getfArrivalType()) {
                result.add(data);
                return false;
            }
            return ArrivalType.MERGE == data.getfArrivalType();
        }).map(ArrivalVouch::getfBarCode).collect(Collectors.toList());
        // 查出所有合并单对应的所有拆分单
        if (!mergeBarList.isEmpty()) {
            Map<String, Object> query = new HashMap<>(2);
            query.put("state", ParentEntity.FSTATE_DELETED);
            query.put("mergeBarList", mergeBarList);
            List<ArrivalVouch> vouchList = arrivalVouchMapper.selectAllByMergeBarList(query);
            if (!vouchList.isEmpty()) result.addAll(vouchList);
        }
        // 过滤出所有默认的单子
        List<ArrivalVouch> vouchList = arrivalVouchList.stream().filter(data -> ArrivalType.DEFAULT == data.getfArrivalType()).collect(Collectors.toList());
        if (!vouchList.isEmpty()) result.addAll(vouchList);
        if (result.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无数据！");
        return result;
    }

    @Override
    public Set<ArrivalVouchVo> selPurByCode(String code) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", code);
        map.put("fState", ParentEntity.FSTATE_DELETED);
        map.put("type", QCAcceptType.ALLOWED);
        map.put("arrivalType", ArrivalType.DEFAULT);
        List<ArrivalVouchVo> arrivalVouchVoList = arrivalVouchMapper.getArLisByPurCode(map);
        if (arrivalVouchVoList.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无数据！");
        Set<ArrivalVouchVo> result = new HashSet<>();
        List<String> mergeBarList = arrivalVouchVoList.stream().filter(data -> {
            if (data.getfArrivalType() != ArrivalType.MERGE) {
                result.add(data);
                return false;
            }
            return data.getfArrivalType() == ArrivalType.MERGE;
        }).map(ArrivalVouchVo::getfBarCode).collect(Collectors.toList());
        // 查出所有合并单对应的所有差分单
        if (!mergeBarList.isEmpty()) {
            Map<String, Object> query = new HashMap<>(3);
            query.put("state", ParentEntity.FSTATE_DELETED);
            query.put("mergeBarList", mergeBarList);
            query.put("barType", ArrivalType.SUBSET);
            List<ArrivalVouchVo> vouchList = arrivalVouchMapper.selectAllByMergeBarVOList(query);
            if (!vouchList.isEmpty()) result.addAll(vouchList);
        }
        // 过滤出所有默认的单子
        List<ArrivalVouchVo> vouchList = arrivalVouchVoList.stream().filter(data -> ArrivalType.DEFAULT == data.getfArrivalType()).collect(Collectors.toList());
        if (!vouchList.isEmpty()) result.addAll(vouchList);
        if (result.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无数据！");
        return result;
    }

    @Override
    @Transactional
    public void cancelAv(String fId) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        String barCode = arrivalVouchMapper.selectArrivalBarCodeById(fId);
        if (StrUtil.isBlank(barCode)) throw new BusinessException("撤销的到货单不存在！");
        String uid = loginUserRedisService.getUser().getFuserid();
        map.put("uid", uid);
        map.put("now", LocalDateTime.now());
        map.put("type", QCAcceptType.ALLOWED);
        map.put("fId", fId);
        // 修改状态
        arrivalVouchMapper.updateAvByFid(map);
        // 删除日志
        logMapper.deleteById(barCode);
    }

    @Override
    public ArrivalRepositoryVo getRepository(ArrivalRepository dto) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("state", ParentEntity.FSTATE_DELETED);
        map.put("barCode", dto.getBarCode());
//        map.put("type", QCAcceptType.ALLOWED);
        List<ArrivalVouch> arrivalVouchList = arrivalVouchMapper.getRepository(map);
        if (arrivalVouchList.isEmpty()) throw new BusinessException("暂无数据！");
        for (ArrivalVouch arrivalVouch : arrivalVouchList) {
            if (arrivalVouch.getfQCAceptType() == QCAcceptType.REFUSED) {
                throw new BusinessException("该条码质检不合格！");
            }
            if (arrivalVouch.getfQCAceptType() == QCAcceptType.STORAGE) {
                throw new BusinessException("该条码已经入库！");
            }
        }
        List<ArrivalRepositoryBody> bodies = new ArrayList<>();
        ArrivalVouch one = arrivalVouchList.get(0);
        dto.setcVenCode(one.getfCVenCode());
        String time = LocalDate.now().toString();
        for (ArrivalVouch arrivalVouch : arrivalVouchList) {
            ArrivalRepositoryBody repositoryBody = new ArrivalRepositoryBody();
            repositoryBody.setCInvCode(arrivalVouch.getFclnvCode());
            repositoryBody.setITaxRate(BigDecimal.ZERO);
            repositoryBody.setTaxUnitPrice(BigDecimal.ZERO);
            repositoryBody.setISum(BigDecimal.ZERO);
            repositoryBody.setCBatch(arrivalVouch.getfCBatch());
            repositoryBody.setCVarvCode(arrivalVouch.getfCCode());
            repositoryBody.setDMDate(time);
            repositoryBody.setIQuantity(arrivalVouch.getfFinStockQuantity());
            repositoryBody.setCFree1(arrivalVouch.getfBanbencode());
            repositoryBody.setIPOsID(Integer.parseInt(arrivalVouch.getfIPOsId()));
            repositoryBody.setIArrsId(Integer.parseInt(arrivalVouch.getfAutoId()));
            repositoryBody.setCPosition(arrivalVouch.getfPosition());
            bodies.add(repositoryBody);
        }
        return new ArrivalRepositoryVo(dto, bodies);
    }

    @Override
    @Transactional
    public String saveOtherGoodEntry(Map<String, Object> map) throws Exception {
        return "success";
    }

    @Override
    @Transactional
    public String saveRepository(ArrivalRepositoryVo repository) throws Exception {
        // 查询是否存在已入库
        Map<String, Object> map = new HashMap<>(3);
        map.put("state", ParentEntity.FSTATE_DELETED);
        map.put("barCode", repository.getRepository().getBarCode());
        map.put("type", QCAcceptType.ALLOWED);
        int counts = arrivalVouchMapper.getRepositoryCount(map);
        if (counts == 0) throw new BusinessException("暂无数据！");
        List<ZnInLog> logs = new ArrayList<>();
        repository.getBody().forEach(dtl -> {
            String dtlbarcode = dtl.getDtlbarcode();
            Assert.isBlank(dtlbarcode, "条码号不能为空！");
            logs.add(new ZnInLog(dtlbarcode, JSONUtil.toJsonStr(dtl)));
        });
        if (!logs.isEmpty()) {
            List<String> bars = logMapper.selectCount(
                    logs.stream()
                            .map(ZnInLog::getId)
                            .collect(Collectors.toList())
            );
            if (!bars.isEmpty()) {
                logs.forEach(dtl -> {
                    if (bars.contains(dtl.getId())) {
                        throw new BusinessException("条码-" + dtl.getId() + "-已经入库~");
                    }
                });
            }
        }
        JSONObject params = new JSONObject(repository.getRepository());
        // 设置时间
        JSONArray bodies = new JSONArray(repository.getBody());
        U8Api.formatTime(bodies);
        params.putOpt("Rows", bodies);
        JSONArray objects = new JSONArray();
        objects.add(params);
        U8Api.setAccessTime(objects);
        String body = JSONUtil
                .toJsonStr(objects, Helper.JSON_CONFIG);
        logs.add(new ZnInLog(repository.getRepository().getBarCode() + "___" + IdUtil.objectId(), body));
        // todo 测试环境先注释调
//        log.info("入库单为Json数据为：{}",body);
        String purIn = U8Api.ptsPurIn(body);
//        String purIn = null;
//        String purIn = "success";
        if (Helper.isNotEmpty(purIn)) {
            String fuserid = loginUserRedisService.getUser().getFuserid();
            ArrivalRepository head = repository.getRepository();
            List<ArrivalVouchDto> list = new ArrayList<>();
            repository.getBody().forEach(av -> {
                ArrivalVouchDto arrivalVouchDto = new ArrivalVouchDto(
                        av.getDtlbarcode(),
                        head.getcPTCode(), // 采购类型
                        head.getcRdCode(), // 收发类型
                        head.getcMaker(), // 制单人
                        head.getcDepCode(), // 部门编码
                        head.getcPersonCode(), // 人员编码
                        head.getcMemo(), // 备注
                        av.getIQuantity(),
                        head.getcWhCode(), // 仓库编号
                        head.getcWhName(), // 仓库名称
                        QCAcceptType.STORAGE, // 状态
                        av.getCPosition(), // 储位
                        fuserid, LocalDateTime.now());
                Helper.setEmptyWithNull(arrivalVouchDto);
                list.add(arrivalVouchDto);
            });
            if (!list.isEmpty()) arrivalVouchMapper.updateAvByBarCodeLis(list);
            // 追加日志
            logMapper.insertZnLog(logs);
        }
        return purIn;
    }

    @Override
    public Integer findCurrentIsExistsByPositionCodeAndName(String code, String name) {
        return U8Api.findCurrentIsExistsByPositionCodeAndName(code, name);
    }

//    @Override
//    public String saveRepository(ArrivalRepositoryVo repository) throws Exception {
//        // 查询是否存在已入库
//        Map<String, Object> map = new HashMap<>(3);
//        map.put("state", ParentEntity.FSTATE_DELETED);
//        map.put("barCode", repository.getRepository().getBarCode());
//        map.put("type", QCAcceptType.ALLOWED);
//        ArrivalRep arrivalRep = arrivalVouchMapper.getRepository(map);
//        if (arrivalRep == null) throw new BusinessException("暂无数据！");
//        JSONObject params = new JSONObject(repository.getRepository());
//        // 设置时间
//        JSONArray bodies = new JSONArray(repository.getBody());
//        params.putOpt("Rows", bodies);
//        String body = JSONUtil
//                .toJsonStr(Collections.singletonList(params), Helper.JSON_CONFIG);
//        System.err.println("入库单：" + body);
//        // todo 测试环境先注释调
//        String purIn = U8Api.ptsPurIn(body);
////        String purIn = "success";
//        if (Helper.isNotEmpty(purIn)) {
//            String fuserid = loginUserRedisService.getUser().getFuserid();
//            ArrivalRepository head = repository.getRepository();
//            String position = repository.getBody().get(0).getCPosition();
//            BigDecimal reduce = repository.getBody().stream().reduce(BigDecimal.ZERO, (count, data) -> count.add(data.getIQuantity()), (count, data) -> count);
//            ArrivalVouchDto arrivalVouchDto = new ArrivalVouchDto(head.getBarCode(),
//                    head.getcPTCode(), // 采购类型
//                    head.getcRdCode(), // 收发类型
//                    head.getcMaker(), // 制单人
//                    head.getcDepCode(), // 部门编码
//                    head.getcPersonCode(), // 人员编码
//                    head.getcMemo(), // 备注
//                    reduce, //实发数
//                    head.getcWhCode(), // 仓库编号
//                    head.getcWhName(), // 仓库名称
//                    QCAcceptType.STORAGE, // 状态
//                    position, // 状态
//                    fuserid, LocalDateTime.now());
//            Helper.setEmptyWithNull(arrivalVouchDto);
//            arrivalVouchMapper.updateAvByBarCodeLis(Collections.singletonList(arrivalVouchDto));
//        }
//        return purIn;
//    }

//    @Override
//    @Transactional
//    public String saveOtherGoodEntry(Map<String, Object> map) throws Exception {
//        // 格式化日期
//        JSONObject u8 = U8Api.formatTime(map);
//        // json格式化
//        JSONArray data = u8.getJSONArray("data");
//        // 查询库存对于的时间信息
//        U8Api.setAccessTime(data);
//        // todo 测试环境先注释调
//        U8Api.ptsPurIn(data.toString());
//        List<ArrivalVouchDto> list = new LinkedList<>();
//        String fuserid = loginUserRedisService.getUser().getFuserid();
//        // u8保存成功 就执行后续操作
//        for (Object o : data) {
//            JSONObject head = (JSONObject) o;
//            String whCode = head.getStr("cWhCode");
//            String whName = head.getStr("cWhName");
//            String cRdCode = head.getStr("cRdCode");
//            String cPTCode = head.getStr("cPTCode");
//            String cMaker = head.getStr("cMaker");
//            String depCode = head.getStr("cDepCode");
//            String personCode = head.getStr("cPersonCode");
//            String memo = head.getStr("cMemo");
//            for (Object li : head.getJSONArray("Rows")) {
//                JSONObject entryMap = (JSONObject) li;
//                ArrivalVouchDto arrivalVouchDto = new ArrivalVouchDto((String) entryMap.get("cVarvCode"), // 箱号
//                        cPTCode, // 采购类型
//                        cRdCode, // 收发类型
//                        cMaker, // 制单人
//                        depCode, // 部门编码
//                        personCode, // 人员编码
//                        memo, // 备注
//                        entryMap.getBigDecimal("iQuantity"), //实发数
//                        whCode, // 仓库编号
//                        whName, // 仓库名称
//                        QCAcceptType.STORAGE, // 状态
//                        entryMap.getStr("position"), // 状态
//                        fuserid, LocalDateTime.now());
//                Helper.setEmptyWithNull(arrivalVouchDto);
//                list.add(arrivalVouchDto);
//            }
//        }
//        log.info(JSONUtil.toJsonPrettyStr(list));
//        // 批量修改
//        if (!list.isEmpty()) arrivalVouchMapper.updateAvByBarCodeLis(list);
//        return "success";
//    }
}
